package com.yswwpp.signature.md;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class MD5 {

	public static void main(String[] agre) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		String s = new String("hello world!");
		System.out.println("原始：" + s);
		System.out.println("MD5后_1：" + string2MD5(s));
		System.out.println("MD5后_2：" + EncoderByMd5(s));
	}

	public static String EncoderByMd5(String str) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		// 确定计算方法
		MessageDigest md5 = MessageDigest.getInstance("MD5");

		byte[] arr=md5.digest(str.getBytes("utf-8"));
		System.out.println("数组长度2:"+arr.length);
		// 加密后的字符串
		String newstr = Base64.getEncoder().encodeToString(arr);
		return newstr;
		 //return new BigInteger(1, arr).toString(16);
	}
	
	public static byte[] md5(byte[] originArr) throws NoSuchAlgorithmException
	{
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		return messageDigest.digest(originArr);
	}

	/**
	 * 加密解密算法 执行一次加密，两次解密
	 */
	public static String convertMD5(String inStr) {

		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;

	}

	/***
	 * MD5加码 生成32位md5码
	 */
	public static String string2MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
		{
			byteArray[i] = (byte) charArray[i];
			
		}
			
		byte[] md5Bytes = md5.digest(byteArray);
		
		for (int i = 0; i < md5Bytes.length; i++)
		{
			System.out.print(md5Bytes[i]);
			System.out.print(" ");
			
		}
		
		System.out.println("数组长度1："+md5Bytes.length);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();

	}

}
